#!/bin/bash
TTY=$1
if [ ! -f /tmp/${TTY}.pid ]; then
	id=
	echo $$ > /tmp/${TTY}.pid
	uid=$(echo $(udevadm info --name=/dev/${TTY}|sed -n '/MAJOR/{s/[A-Z: =]*//;p}')*256+$(udevadm info --name=/dev/${TTY}|sed -n '/MINOR/{s/[A-Z: =]*//;p}')|bc)
#	id=${uid}$(date +%s%2N)
	exfile=$(date +%j%H%M)
	while IFS=$ read -r pre gline; do
		if [ ! -z "$gline" ]; then
		IFS=, read -r telegram payload <<< $gline
		if [[ "$telegram" != *"TXT"* ]]; then
			payload=${payload%\**}
#			echo $payload
			if [[ "$payload" != *"\$G"* ]]; then
			  if [ ${#telegram} -eq 5 ]; then
#				echo $payload
				if [[ "$telegram" = *"RMC"* ]]; then
					if [[ "$gline" = *",A,"* ]]; then
						id=${uid}$(date +%s%2N)
						exfile=$(date +%j%H%M)
					else
						id=
						exfile=
					fi
				fi
				if [ ! -z "$id" ]; then
					echo ${uid},${id},$(date +%s%3N),${telegram},\;"${payload}"\; >>/tmp/gps_${uid}_${exfile}
	#				mysql -u gps -pgps -D gps -e "insert into gpsin (uid,id,epoch,telegram,payload) values (${uid},${id},$(date +%s%3N),'${telegram}','${payload}');" #>>/tmp/gps_${uid}_${exfile}
					
				fi
			  fi
			fi
		fi
		fi
	done </dev/${TTY}
fi
